package com.hotdog.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
/**
 * 定义登陆规则
 * 登陆成功,对所有请求放行
 * 登陆成功信息返回
 * 登陆失败信息的返回
 * @author 郭鲁政
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    @Override
    protected void configure(HttpSecurity http) throws Exception {


        //2.登陆成功,对所有请求放行
        http.authorizeRequests().anyRequest().permitAll();
        //3.成功与失败的处理
        http.formLogin().successHandler(successHandler()).failureHandler(failureHandler());

    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean()
            throws Exception {
        return super.authenticationManagerBean();
    }


    /**初始化密码加密对象*/
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();

    }

    /**
     * 成功的方法
     */
    @Bean
    public AuthenticationSuccessHandler successHandler() {
        return (request, response, authentication) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("status", 200);
            map.put("message", "login ok");

            ToJson(response, map);
        };
    }

    /**
     * 失败的方法
     */
    @Bean
    public AuthenticationFailureHandler failureHandler() {
        return (request, response, exception) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("status", 500);
            map.put("message", "fail back");

            ToJson(response, map);
        };
    }

    private void ToJson(HttpServletResponse response, Map map) throws IOException {
        String s = new ObjectMapper().writeValueAsString(map);
        PrintWriter writer = response.getWriter();
        writer.println(s);
        writer.flush();
    }

}
